package common;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import models.Article;
import models.ArticleTag;
import models.Tag;
import mx.bigdata.jcalais.CalaisObject;
import mx.bigdata.jcalais.CalaisResponse;

import org.jsoup.select.Elements;

import common.cache.CacheManager;
import common.cache.CacheMode;
import common.rssReader.Rss;
import common.rssReader.RssItem;
import common.rssReader.RssReader;

import play.jobs.Every;
import play.jobs.Job;
import play.libs.F.Promise;

@Every("5min")
public class NewsFetcher extends Job {

	public static Date lastRssReadTime = null;

	@Override
	public void doJob() throws Exception {

		
		System.out.println("rssReader Basladi");
		RssReader rssReader = RssReader.getInstance();
		ArticleReader articleReader = ArticleReader.getInstance();
		Rss rss = rssReader.readRss(RssReader.lastReadedTime);
		RssReader.lastReadedTime = DateUtils.getNow();

		Long startTime = System.currentTimeMillis();
		if (rss.getRssItems() != null && rss.getRssItems().size() > 0) {

			for (RssItem item : rss.getRssItems()) {

				// Promise<Elements> element = new
				// ArticleReaderJob(item.getLink()).now();
				Elements element = articleReader.getArticle(item.getLink(),
						"5000");

				if (element != null) {
					Article article = Article.findOrCreateArticleByTitle(item
							.getTitle());
					// save article
					if (article.isPersistent()) {
						ArticleTag.delete("articleID=?", article.getId());
						System.out
								.println("the article update and its tags were deleted");
					}
					article.saveArticle(item.getTitle(), item.getDesc(),
							element.toString(), item.getDate());

					// get article's tags
					Iterable<CalaisObject> tags = TagFetcher.getTags(element
							.text());
					if (tags != null) {
						for (CalaisObject entity : tags) {
							Tag tag = Tag.findOrCreate(entity.getField("name"));
							tag.save();

							ArticleTag at = new ArticleTag(article.getId(),
									tag.getId());
							at.save();
						}
					}
				}

				System.out.println(element);
				System.out.println("------------------" + item.getLink()
						+ "------------------");
				System.out.println();
				System.out.println();
			}

		}
		Long endTime = System.currentTimeMillis();
		System.err.println("---------------");
		System.err.println("PASSED TIME = " + (endTime - startTime));
		System.err.println("---------------");
		System.out.println("rssReader Bitti.");
	
       List<Article> articleList = Article.getArticleOrderByDate(0);
       CacheManager.setCacheItem("articleList1"+0,articleList,CacheMode.CentralCache);
	}

}
